$(document).ready(function() {
  require(["inputdrop", "asset"], function(inputdrop, asset) {
    var list_col = [
      { name: "", text: "", hideSearch: "hide", width: 3 },
      { text: "姓名", name: "name", align: "left", width: 15 , tip:true},
      {
        text: "用户名",
        name: "username",
        align: "left",
        width: 15,
        tip:true,
        searchRender: function(el) {
          el.append(
            '<input type="text" class="form-control input-sm" search-data="userName">'
          );
        }
      },
      { text: "角色", name: "roleName", align: "left", width: 10, tip:true },
      { text: "邮件地址", name: "email", align: "left", width: 10, tip:true },
      { text: "登录次数", name: "loginNum", align: "left", width: 10 },
      { text: "最近一次登录IP", name: "lastLoginIp", align: "left", width: 10 },
      {
        text: "账号状态",
        name: "state",
        align: "left",
        width: 10,
        render: function(text) {
          return text == 1 ? "启用" : "停用";
        }
      },
      {
        text: "最近一次登录时间",
        name: "loginTime",
        align: "left",
        width: 15,
        render: function(text) {
          var content;
          if (text) {
            content = new Date(+text).Format("yyyy-MM-dd hh-mm-ss");
          } else {
            content = "";
          }
          return content;
        }
      }
    ];
    var index_oper = [
      { icon: "rh-icon rh-edit", text: "编辑", aclick: edit_template_init },
      {
        icon: "rh-icon rh-unlock",
        text: "启用",
        aclick: index_list_lock,
        customRender: function(rowData) {
          return {
            icon:
              rowData.state == "1" ? "rh-icon rh-unlock" : "rh-icon rh-lock",
            text: rowData.state == "1" ? "停用" : "启用"
          };
        }
      },
      {
        icon: "rh-icon rh-delete",
        text: "删除",
        aclick: delete_list_init,
        isShow: function(rowData) {
          if (rowData.system) {
            return false;
          } else {
            return true;
          }
        }
      }
    ];
    var gridOptions={
      header: list_col,
      oper: index_oper,
      operWidth: "130px",
      // url: "api/public/user/list",
      url: "api/user/list",
      type: "xd",
      dataKey: "list",
      hasBorder: false,
      hideSearch: true,
      dbClick: detail_template_init,
      // dbIndex: 1,
      autoHeight : true,
      showCount : true       
    }
    var username = sessionStorage.getItem("username");
    if (username == "sysmanager") {
    } else {
      $("#btnGroup").hide();
      index_oper = [
        { icon: "rh-icon rh-edit", text: "编辑", aclick: edit_template_init },
        {
          icon: "rh-icon rh-delete",
          text: "删除",
          aclick: delete_list_init,
          isShow: function(rowData) {
            if (rowData.system) {
              return false;
            } else {
              return true;
            }
          }
        }
      ];
      gridOptions.allowCheckBox=false
    }
    var key;

    event_init();

    user_list({ paramObj: { keyWords: key }, isLoad: true, maskObj: "body" });

    index_search_div_remove_click(user_list, {
      paramObj: null,
      isLoad: true,
      maskObj: "body"
    });

    function event_init() {
      $("input[placeholder]").placeholder();
      $("#add_btn").click(function() {
        edit_template_init();
      });
      $("#searchIcon").click(function() {
         key = $("#searchKey").val();
        user_list({
          paramObj: { keyWords: key },
          isLoad: true,
          maskObj: "body"
        });
      });
      $("#searchKey").keydown(function(event) {
        if (event.keyCode == 13) {
          $("#searchIcon").trigger("click");
        }
      });
      $("#sec_setting_btn").click(function() {
        sec_setting_template_init();
      });

      asset.user_init();
    }

    function user_list(option) {
      gridOptions.paramObj= option.paramObj
      gridOptions.isLoad= option.isLoad
      gridOptions.maskObj= option.maskObj
      g_grid.render($("#table_div"), gridOptions);
    }

    function delete_list_init(rowData) {
      var aUser = [];
      var oUser = {};
      oUser.id = rowData.id;
      aUser.push(oUser);
      if(rowData.state==1){
        g_dialog.operateAlert(null, "启用用户无法删除，请先停用该用户", 'error');
        return false
      }
      g_dialog.operateConfirm("用户账号删除后将不能恢复", {
        saveclick: function() {
          xd_ajax_post({
            url: "api/user/delete",
            paramObj: aUser,
            successCallBack: function(data) {
              user_list({
                paramObj: { keyWords: key },
                isLoad: true,
                maskObj: "body"
              });
              g_dialog.operateAlert(null, "操作成功！");
            }
          });
        }
      });
    }

    function edit_template_init(rowData) {
      var title = rowData ? "用户修改" : "用户添加";
      $.ajax({
        type: "GET",
        url: "module/sys_config/user_manage_tpl.html",
        success: function(data) {
          g_dialog.dialog($(data).find("[id=user_edit_template]"), {
            width: "560px",
            init: init,
            initAfter: initAfter,
            title: title,
            saveclick: save_click
            // autoHeight: "autoHeight"
          });
        }
      });

      function init(el) {
        if (rowData) {
          $("[type='password']").attr("placeholder", "输入密码来更改密码");
          rowData.password = "";
          el.umDataBind("render", rowData);
        }
      }
    
      function initAfter(el) {
        //  初始化之后的操作
        xd_ajax_get({
          url: "api/role/list",
          paramObj: "",
          successCallBack: function(data) {
            var dataList = [];
            data.list.forEach(function(item) {
              dataList.push({ id: item.id, text: item.roleName });
            }, this);
            $("#roleId").select2({
              data: dataList,
              placeholder: "请选择"
            });
            if (rowData) {
              $("[type='password']").placeholder();
              $(".pass")
                .eq(0)
                .text("修改密码：");
              $(".pass").removeClass("required");
              $("#newPwd").attr("reg", "minLength:6,maxLength:20,password");
              $("#surePass").attr("reg", "equalsTo:newPwd,password");
              $("#newPwd").blur(function() {
                if ($("#newPwd").val() !== "") {
                  $("#surePass").attr(
                    "reg",
                    "notempty,equalsTo:newPwd,password"
                  );
                } else {
                  $("#surePass").attr("reg", "equalsTo:newPwd,password");
                  $("#surePass").removeAttr("tip");
                  $("#surePass").removeClass("input_validation-failed");
                }
              });
              el.umDataBind("render", rowData);
              //  $("#roleId").val(rowData.roleId);
              //  $("#select2-roleId-container").html(rowData.roleName);
            }
          }
        });
      }

      function save_click(el, saveObj) {
        var url = "api/user/save";
        rowData && (url = "api/user/edit");
        if (validateForm($("#userForm"))) {
          xd_ajax_post({
            url: url,
            paramObj: saveObj,
            // maskObj: el,
            successCallBack: function(data) {
              g_dialog.operateAlert();
              g_dialog.hide(el);
              user_list({
                paramObj: { keyWords: key },
                isLoad: true,
                maskObj: "body"
              });
              // g_grid.refresh($("#table_div"));
            }
          });
        }
      }
    }

    function detail_template_init(rowData) {
      // alert(2)
    }

    function index_list_lock(rowData) {
      var lock_msg = "是否停用该用户？";
      var unlock_msg = "是否启用该用户？";
      var sucessMsg="用户账号停用（启用）成功"
      msg = rowData.state == "1" ? lock_msg : unlock_msg;
      var aUser = [];
      var oUser = {};
      oUser.id = rowData.id;
      rowData.state == 1 ? (oUser.state = 0) : (oUser.state = 1);
      aUser.push(oUser);
      g_dialog.operateConfirm(msg, {
        saveclick: function() {
          xd_ajax_post({
            url: "api/user/changeState",
            paramObj: aUser,
            maskObj: "body",
            successCallBack: function(data) {
              // g_dialog.operateAlert(sucessMsg);
              g_dialog.operateAlert(null, sucessMsg);
              user_list({
                paramObj: { keyWords: key },
                isLoad: true,
                maskObj: "body"
              });
            }
          });
        }
      });
    }
    function user_batch_operate(type) {
      var row_data = g_grid.getData($("#table_div"), { chk: true });
      if (row_data.length < 1) {
        if(type==1){
          g_dialog.operateAlert(null, "请选择要启用的用户",'error');
        }else{
          g_dialog.operateAlert(null, "请选择要停用的用户",'error');
        }
        return false;
      }
      var aUser = [];
      row_data.forEach(function(item) {
        var oUser = {};
        oUser.id = item.id;
        oUser.state = type;
        aUser.push(oUser);
      }, this);
      var message = "确认停用用户?";
      if (type) {
        message = "确认启用用户?";
      }
      g_dialog.operateConfirm(message, {
        saveclick: function() {
          xd_ajax_post({
            url: "api/user/changeState",
            paramObj: aUser,
            successCallBack: function(data) {
              user_list({
                paramObj: { keyWords: key },
                isLoad: true,
                maskObj: "body"
              });
              g_dialog.operateAlert(null, "操作成功！");
            }
          });
        }
      });
    }
    $("#batch_stop").click(function() {
      user_batch_operate(0);
    });
    $("#batch_enable").click(function() {
      user_batch_operate(1);
    });

  });
});
